package com.itttq.kb.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.itttq.kb.model.to.ResultTo;
import com.itttq.kb.utils.CompressImgUtil;
import com.itttq.kb.utils.Constants;
import com.itttq.kb.utils.VerifyCodeUtil;

@RestController
public class CommonController extends GenericController {
	private static final long serialVersionUID = 2574898959274772468L;
	// 图片上传目录，
	@Value("${path.file.upload.img}")
	public String imgUploadPath;
	// 图片URL地址，http://img.xx.com
	@Value("${path.file.url.img}")
	public String imgUrlPath;

	/**
	 * 上传单个图片文件<br>
	 * 这里这里用的是MultipartFile file参数,所以前台就要用< input type="file" name="file"/ >,参数名称file与input的name属性名对应
	 * @param dir	上传目录
	 * @param file	文件内容
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
	@ResponseBody
	public ResultTo uploadImage(Integer dirType, MultipartFile file) throws IOException {
		ResultTo rt = new ResultTo(ResultTo.FAIL);
		if (file.isEmpty() || null == dirType || dirType < 1 || null == Constants.UPLOAD_DIR.get(dirType)) {
			rt.setCode(ResultTo.PARAM_INCORRECT);
			rt.setMsg("传入参数不正确！");
			return rt;
		}
		String dir = Constants.UPLOAD_DIR.get(dirType);
		String fileType = !file.getOriginalFilename().contains(Constants.SEPARATOR_SPOT) ? "" 
				: file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(Constants.SEPARATOR_SPOT));
		if(!Constants.IMG_TYPES.contains(fileType)) {
			// 判断类型
			rt.setCode(ResultTo.FILE_TYPE);
			rt.setMsg("文件类型错误，只支持：png、gif、jpg、jpeg");
		} else {
			try {
				String filePath = Constants.SEPARATOR_BACKSLASH + dir + Constants.SEPARATOR_BACKSLASH 
						+ Constants.getFilenameByTime() +fileType;
				CompressImgUtil.compress(file, 0.7f, 600, imgUploadPath + filePath);
				rt.setCode(ResultTo.SUCCESS);
				rt.setMsg(imgUrlPath + filePath);
			} catch (Exception e) {
				e.printStackTrace();
				rt.setCode(ResultTo.PARAM_INCORRECT);
				rt.setMsg("文件上传失败，请重试");
			}
		}
		return rt;
	}
	/**
	 * UE上传单个图片文件<br>
	 * 这里这里用的是MultipartFile file参数,所以前台就要用< input type="file" name="file"/ >,参数名称file与input的name属性名对应
	 * @param dir	上传目录
	 * @param file	文件内容
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/ueUploadImg", method = RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> ueUploadImage(Integer dirType, MultipartFile file) throws IOException {
		ResultTo rt = uploadImage(dirType, file);
		Map<String,Object> result=new HashMap<String,Object>();//  
		if(rt.getCode()==ResultTo.SUCCESS) {
			result.put("name", file.getOriginalFilename());//新的文件名  
	        result.put("originalName", file.getOriginalFilename());//原始文件名  
	        result.put("size", file.getSize());  
	        result.put("state", "SUCCESS");  
	        result.put("url", rt.getMsg());
		} else {
			
		}
	    return result;  
	}
	/**
	 * 获取验证码，验证码有两类：纯字母、加减乘计算
	 * 
	 * @param request
	 * @param response
	 * @Author 迷蝶
	 * @return void
	 */
	@RequestMapping("vc")
	public void getValidateCode(HttpServletRequest request, HttpServletResponse response) {
		response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        String verifyCode = VerifyCodeUtil.generateVerifyCode(4);
        /**
         * 下面是准备使用两种验证方式，纯验证码和加减乘法
        // 根据获取纳秒级来判断获取哪种验证方式，目前就两种：验证码 和 加减法
        Long nano = System.nanoTime();
        String result=null;
        switch (nano.intValue() % 2) {
        	case 0:
        		// 生成随机字串
        		result = verifyCode = VerifyCodeUtil.generateVerifyCode(4);
        		break;
        	case 1:
        		// 生成加减乘法，先简单生成。后续优化
        		int i,j;
        		switch(nano.intValue() % 3) {
        			case 1 :
        				// 加法
        				i = Constants.genRandomNum(0,9);
                		j = Constants.genRandomNum(0,9);
                		verifyCode = i + " + " + j + "=";
                		result = String.valueOf(i + j);
                		break;
        			case 2:
        				// 减法，为了简单不出现负数。保证减数比被减数小
        				i = Constants.genRandomNum(4,9);
                		j = Constants.genRandomNum(0,i);
                		verifyCode = i + " - " + j + "=";
                		result = String.valueOf(i - j);
                		break;
        			case 0:
        				// 乘法
        				i = Constants.genRandomNum(0, 9);
        				j = Constants.genRandomNum(0, 9);
        				verifyCode = i + " x " + j + "=";
        				result = String.valueOf(i * j);
                		break;
        		}
        		break;
        }
        */
        //存入会话session 
        this.setSession(request, Constants.SESSION_CODE_GETPWD, verifyCode); 
        //生成图片 
        int w = 100, h = 35; 
        try {
			VerifyCodeUtil.outputImage(w, h, response.getOutputStream(), verifyCode);
		} catch (IOException e) {
			e.printStackTrace();
		} 
	}
}
